/*!
 * uu-editor v1.0.2
 * Copyright 2014 www.docswf.com
 * Licensed under GPL
 */

(function($) {
    var editor;
    var iframe;
    var issource;
    var issimple;
    var isfull;
    $.fn.iUUEditor = function(options) {
        var defaults = {
            width: '900px',
            height: '600px',
            context: '',
            conver: false,
            font: ['宋体', '新宋体', '仿宋,仿宋_GB2312', '楷体,楷体_GB2312', '黑体', '微软雅黑', '隶书', '幼圆', 'Arial', 'Arial Black', 'Courier New', 'Georgia', 'Helvetica', 'Times New Roman', 'Tahoma', 'Impact', 'Verdana'],
        };
        $.fn.iUUEditor.opts = $.extend({}, defaults, options);
        return this.each(function() {
            initEditor($(this));
            getEditor();
            initEvents();
            editor.body.innerHTML = $.fn.iUUEditor.opts.context;
        });
    };
    $.fn.iUUEditor.opts;
    $.fn.iUUEditor.Text;

    var initEditor = function($this) {
        var color = '<table cellpadding="0px"cellspacing="5px"><tbody><tr><td style="background-color: #000000"></td><td style="background-color: #993300"></td><td style="background-color: #333300"></td><td style="background-color: #003300"></td><td style="background-color: #003366"></td><td style="background-color: #000080"></td><td style="background-color: #333399"></td><td style="background-color: #333333"></td></tr><tr><td style="background-color: #800000"></td><td style="background-color: #FF6600"></td><td style="background-color: #808000"></td><td style="background-color: #008000"></td><td style="background-color: #008080"></td><td style="background-color: #0000FF"></td><td style="background-color: #666699"></td><td style="background-color: #808080"></td></tr><tr><td style="background-color: #FF0000"></td><td style="background-color: #FF9900"></td><td style="background-color: #99CC00"></td><td style="background-color: #339966"></td><td style="background-color: #33CCCC"></td><td style="background-color: #3366FF"></td><td style="background-color: #800080"></td><td style="background-color: #999999"></td></tr><tr><td style="background-color: #FF00FF"></td><td style="background-color: #FFCC00"></td><td style="background-color: #FFFF00"></td><td style="background-color: #00FF00"></td><td style="background-color: #00FFFF"></td><td style="background-color: #00CCFF"></td><td style="background-color: #993366"></td><td style="background-color: #C0C0C0"></td></tr><tr><td style="background-color: #FF99CC"></td><td style="background-color: #FFCC99"></td><td style="background-color: #FFFF99"></td><td style="background-color: #CCFFCC"></td><td style="background-color: #CCFFFF"></td><td style="background-color: #99CCFF"></td><td style="background-color: #CC99FF"></td><td style="background-color: #FFFFFF"></td></tr></tbody></table>';
        var font = getfont();
        $this.html('<div class="uu-editor-html" style="width:' + $.fn.iUUEditor.opts.width + ';height:' + $.fn.iUUEditor.opts.height + '"><div class="uu-editor-toolbar"><span class="uu-editor-font"title="选择字体"><h7 class="uu-editor-h7">宋体</h7>' + font + '</span><span class="uu-editor-size"title="选择字体大小"><h7 class="uu-editor-h7">14px</h7><i class="uu-editor-arrowbtn"></i><ul class="uu-editor-sizebox"><li style="font-size:10px;height:20px;line-height:20px">10px</li><li style="font-size:14px;height:25px;line-height:25px">14px</li><li style="font-size:16px;height:30px;line-height:30px">16px</li><li style="font-size:18px;height:35px;line-height:35px">18px</li><li style="font-size:24px;height:40px;line-height:40px">24px</li><li style="font-size:32px;height:45px;line-height:45px">32px</li><li style="font-size:48px;height:50px;line-height:50px">48px</li></ul></span><a class="uu-editor-bold"title="加粗"></a><a class="uu-editor-italic"title="斜体"></a><a class="uu-editor-underline"title="下划线"></a><a class="uu-editor-strikethrough"title="删除线"></a><span class="sp"></span><span class="uu-editor-forecolor"title="设置字体颜色">' + color + '</span><span class="uu-editor-backcolor"title="设置字体背景">' + color + '</span><span class="sp"></span><a class="uu-editor-insertHorizontalRule"title="插入横线"></a><a class="uu-editor-insertImage"title="插入图片"></a><a class="uu-editor-table"title="插入表格"></a><a class="uu-editor-full"title="全屏"></a><span class="sp"style="float:right"></span><a class="uu-editor-simple"title="简单"></a></div><div class="uu-editor-toolbar uu-editor-barsp"><a class="uu-editor-justifyleft"title="左对齐"></a><a class="uu-editor-justifycenter"title="居中对齐"></a><a class="uu-editor-justifyright"title="右对齐"></a><a class="uu-editor-justifyfull"title="两端对齐"></a><span class="sp"></span><a class="uu-editor-insertunorderedlist"title="有序列表"></a><a class="uu-editor-insertorderedlist"title="无须列表"></a><a class="uu-editor-indent"title="增加缩进"></a><a class="uu-editor-outdent"title="减小缩进"></a><span class="sp"></span><a class="uu-editor-createLink"title="插入连接"></a><a class="uu-editor-unLink"title="删除连接"></a><span class="sp"></span><a class="uu-editor-subscript"title="上标"></a><a class="uu-editor-superscript"title="下标"></a><span class="sp"></span><a class="uu-editor-source"title="源码"></a><a class="uu-editor-undo"title="撤销"></a><a class="uu-editor-redo"title="重做"></a></div><div class="uu-editor-conver"></div><div class="uu-editor-box"><div class="uu-editor-boxhead"><div class="uu-editor-boxtitle">插入表格</div><div class="uu-editor-boxclose">&times;</div></div><div class="uu-editor-boxbody"></div><div class="uu-editor-boxfoot"><div class="uu-editor-boxcancel">取消</div><div class="uu-editor-boxok">确定</div></div></div><iframe id="uu-editor-iframe"></iframe><textarea id="uu-editor-text"></textarea></div>');
        $(".uu-editor-toolbar,.uu-editor-toolbar *").attr("unselectable", "on");
        editorsize( $.fn.iUUEditor.opts.height,$.fn.iUUEditor.opts.width);
    };

    var getEditor = function() {
        iframe = document.getElementById("uu-editor-iframe");
        editor = iframe.contentDocument || iframe.contentWindow.document;
        editor.designMode = "on";
    };

    var doCommand = function(command, arg) {
        try {
            editor.execCommand(command, false, arg);
        } catch (e) {
            alert(e);
        }
    };

    var initEvents = function() {
        $(".uu-editor-toolbar").mouseover(function(e) {
            if (e.target.tagName.toLowerCase() == "a") {
                $(e.target).addClass("uu-editor-hover");
            }
            if (e.target.tagName.toLowerCase() == "li") {
                $(e.target).css("background-color", "#D6E6F2");
            }
        }).mouseout(function(e) {
            if (e.target.tagName.toLowerCase() == "a") {
                $(e.target).removeClass("uu-editor-hover");
            }
            if (e.target.tagName.toLowerCase() == "li") {
                $(e.target).css("background-color", "#fff");
            }
        });

        $(".uu-editor-toolbar span").hover(function() {
            $(this).addClass("uu-editor-hover");
        }, function(e) {
            var $this = $(this);
            var className = this.className.toLowerCase().split(" ")[0].split("-")[2];
            switch (className) {
                case "font":
                case "size":
                    $this.find("ul").slideUp();
                    break;
                case "forecolor":
                case "backcolor":
                    $this.find("table").hide();
                    break;
            }
            $(this).removeClass("uu-editor-hover");
        });

        $(iframe).mouseleave(function() {
            $.fn.iUUEditor.Text = editor.body.innerHTML;
        });

        $(".uu-editor-toolbar").click(function(e) {
            iframe.contentWindow.focus();
            var $this = $(e.target);
            var tagName = e.target.tagName.toLowerCase();
            var className = e.target.className.toLowerCase().split(" ")[0].split("-")[2];
            if (tagName == "li") {
                $this.parent().slideUp("fast");
                $this.parent().parent().find("h7").text($this.text());
                var com = $(e.target).attr("style");
                var arg = com.split(";")[0].split(":")[1];
                if (com.split(":")[0] == "font-family") {
                    doCommand("fontName", arg);
                } else {
                    doCommand("fontSize", arg.indexOf("10px") > -1 ? "1" : arg.indexOf("40px") > -1 ? "2" : arg.indexOf("16px") > -1 ? "3" : arg.indexOf("18px") > -1 ? "4" : arg.indexOf("24px") > -1 ? "5" : arg.indexOf("32px") > -1 ? "6" : arg.indexOf("48px") > -1 ? "7" : "2");
                }
                return false;
            }
            if (tagName == "td") {
                doCommand($this.parents("span").attr("class").toLowerCase().split(" ")[0].split("-")[2], $this.attr("style").split(":")[1]);
                return false;
            }
            switch (className) {
                case "bold":
                case "italic":
                case "underline":
                case "strikethrough":
                case "justifyleft":
                case "justifycenter":
                case "justifyright":
                case "justifyfull":
                case "insertunorderedlist":
                case "insertorderedlist":
                case "indent":
                case "outdent":
                case "undo":
                case "redo":
                case "inserthorizontalrule":
                case "unlink":
                case "subscript":
                case "superscript":
                    doCommand(className);
                    break;
                case "font":
                case "size":
                    $this.find("ul").stop().slideToggle("fast");
                    break;
                case "h7":
                    $this.parent().find("ul").stop().slideToggle("fast");
                    break;
                case "forecolor":
                case "backcolor":
                    $this.find("table").toggle();
                    break;
                case "insertimage":
                    insertImage();
                    break;
                case "createlink":
                    if (/trident/i.exec(navigator.userAgent)) {
                        doCommand(className, prompt("请输入连接网址", "http://"));
                    } else {
                        insertLink();
                    }
                    break;
                case "table":
                    insertTable();
                    break;
                case "source":
                    if (issource) {
                        $(iframe).show();
                        $("#uu-editor-text").hide();
                        editor.body.innerHTML = $("#uu-editor-text").val();
                        iframe.contentWindow.focus();
                    } else {
                        $(iframe).hide();
                        $("#uu-editor-text").show();
                        $("#uu-editor-text").val(editor.body.innerHTML);
                        $("#uu-editor-text").focus();
                    }
                    issource = !issource;
                    break;
                case "full":
                    if (isfull) {
                        $this.css("background-position", "-276px -36px");
                        $this.attr("title", "全屏");
                        $(".uu-editor-html").css({
                            "position": "static"
                        });
                        editorsize($.fn.iUUEditor.opts.height, $.fn.iUUEditor.opts.width);
                    } else {
                        $this.css("background-position", "-306px -36px");
                        $this.attr("title", "还原");
                        $(".uu-editor-html").css({
                            "position": "fixed",
                            "top": "0",
                            "left": "0"
                        });
                        editorsize($(window).height(), $(window).width());
                    }
                    isfull = !isfull;
                    break;
                case "simple":
                    if (issimple) {
                        $this.css("background-position", "-214px -34px");
                        $this.attr("title", "简单");
                        $(".uu-editor-barsp").stop().slideDown();
                    } else {
                        $this.css("background-position", "-244px -34px");
                        $this.attr("title", "高级");
                        $(".uu-editor-barsp").stop().slideUp();
                    }
                    issimple = !issimple;
                    break;
            }
        });

        $(".uu-editor-boxclose,.uu-editor-boxcancel").click(function() {
            $(".uu-editor-conver,.uu-editor-box").hide();
        });

        $(".uu-editor-boxok").click(function() {
            $(".uu-editor-conver,.uu-editor-box").hide();
            iframe.contentWindow.focus();
            var link = $("#uu-editor-createlink").val();
            var imgurl = $("#uu-editor-imgurl").val();
            var imgdata = $("#uu-editor-imgdata").val();
            var trows = $("#uu-editor-trows").val();
            if (link) {
                doCommand("createlink", link);
            } else if (imgurl) {
                doCommand("insertimage", imgurl);
            } else if (imgdata) {
                var img = $("#uu-editor-imgdata")[0].files[0];
                if (/^image\//.test(img.type)) {
                    $.when(toBase64(img)).done(function(data) {
                        doCommand('insertimage', data);
                    }).fail(function(e) {
                        alert("上传失败");
                    });
                } else {
                    alert("上传的不是图片");
                }
            } else if (trows) {
                insertHTML(createTable());
            }
        });

        if (/msie/i.exec(navigator.userAgent)) {
            var bookmark;
            $(iframe).on("beforedeactivate", function() {
                var range = editor.selection.createRange();
                bookmark = range.getBookmark();
            });
            $(iframe).on("activate", function() {
                if (bookmark) {
                    var range = editor.body.createTextRange();
                    range.moveToBookmark(bookmark);
                    range.select();
                    bookmark = null;
                }
            });
        }

        $(window).resize(conversize);
        $(window).resize(boxposition);
    };

    var insertLink = function() {
        $(".uu-editor-boxtitle").html("插入连接");
        $(".uu-editor-boxbody").html('<label>连接网址：</label><input type="text" id="uu-editor-createlink" class="uu-editor-datatxt" placeholder="http://" />');
        showbox();
    };

    var insertImage = function() {
        if (typeof FileReader == 'undefined') {
            $(".uu-editor-boxbody").html('<label>图片网址：</label><input type="text" id="uu-editor-imgurl" class="uu-editor-datatxt" placeholder="http://" />');
        } else {
            $(".uu-editor-boxbody").html('<input type="file" id="uu-editor-imgdata" class="uu-editor-datatxt" accept="image/gif,image/jpeg,image/bmp,image/x-png"/>');
        }
        showbox();
    };

    var insertTable = function() {
        $(".uu-editor-boxtitle").html("插入表格");
        $(".uu-editor-boxbody").html('<table><tr><td>行数</td><td><input type="number" id="uu-editor-trows" style="width:40px" value="3"/></td><td>行</td><td width="50px;"></td><td>列数</td><td><input type="number" id="uu-editor-tcols" style="width:40px" value="3"/></td><td>列</td></tr><tr><td>宽度</td><td><input type="number" id="uu-editor-twidth" style="width:40px" value="200"/></td><td>px</td><td></td><td>边框</td><td><input type="number" id="uu-editor-tborder" style="width:40px" value="1"/></td><td>px</td></tr><tr><td>间距</td><td><input type="number" id="uu-editor-tmargin" style="width:40px" value="0"/></td><td>px</td><td></td><td>边距</td><td><input type="number" id="uu-editor-tpadding" style="width:40px" value="0"/></td><td>px</td></tr></table>');
        showbox();
    };

    var insertHTML = function(html) {
        if (/msie/i.exec(navigator.userAgent)) {
            editor.selection.createRange().pasteHTML(html)
        } else if (/trident/i.exec(navigator.userAgent)) {
            var s = iframe.contentWindow.getSelection();
            var r = s.getRangeAt(0);
            var f = r.createContextualFragment(html),
                l = f.lastChild;
            r.insertNode(f);
            r.setEndAfter(l);
            r.setStartAfter(l);
            s.removeAllRanges();
            s.addRange(r);
        } else {
            doCommand("insertHTML", html);
        }
    };

    var createTable = function() {
        var trows = $("#uu-editor-trows").val(),
            tcols = $("#uu-editor-tcols").val(),
            twidth = $("#uu-editor-twidth").val(),
            tborder = $("#uu-editor-tborder").val(),
            tmargin = $("#uu-editor-tmargin").val(),
            tpadding = $("#uu-editor-tpadding").val();
        var table = '<table border="' + tborder + '" width="' + twidth + '" cellpadding="' + tpadding + '" cellspacing="' + tmargin + '">';
        for (var r = 0; r < trows; r++) {
            table += '<tr>';
            for (var c = 0; c < tcols; c++) {
                table += '<td>&nbsp;</td>';
            }
            table += '</tr>';
        }
        table += '</table>';
        return table;
    };

    var toBase64 = function(file) {
        var def = $.Deferred(),
            reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
            def.resolve(e.target.result);
        };
        reader.onerror = def.reject;
        reader.onprogress = def.notify;
        return def.promise();
    };

    var conversize = function() {
        $(".uu-editor-conver").height($(document).innerHeight());
        $(".uu-editor-conver").width($(document).innerWidth());
        if (!$.fn.iUUEditor.opts.conver) $(".uu-editor-conver").css("opacity", "0");
    };

    var boxposition = function() {
        var wh = $(window).height();
        var ww = $(window).width();
        var bh = $(".uu-editor-box").outerHeight();
        var bw = $(".uu-editor-box").outerWidth();
        $(".uu-editor-box").css({
            "left": (ww - bw) / 2,
            "top": (wh - bh) / 2
        });
    };

    var editorsize = function(height, width) {
        $(".uu-editor-html").css({
            "height": parseInt(height),
            "width": parseInt(width)
        });
        $("#uu-editor-iframe,#uu-editor-text").css("height", parseInt(height) - 61);
    };

    var showbox = function() {
        conversize();
        boxposition();
        $(".uu-editor-box,.uu-editor-box *[type!='text']").attr("unselectable", "on");
        $(".uu-editor-box,.uu-editor-box *[type!='number']").attr("unselectable", "on");
        $(".uu-editor-conver,.uu-editor-box").show();
    };

    var getfont = function() {
        var fonts = $.fn.iUUEditor.opts.font;
        var font = '<ul>';
        for (var f in fonts) {
            fonts[f] == '仿宋,仿宋_GB2312' ? fonts[f] = '仿宋_GB2312' : "";
            fonts[f] == '楷体,楷体_GB2312' ? fonts[f] = '楷体_GB2312' : "";
            font += '<li style="font-family:' + fonts[f] + '">' + fonts[f] + '</li>';
        }
        return font += '</ul>';
    };

})(jQuery);